package com.ruoyi.project.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.ruoyi.framework.config.WxAccessTokenManager;
import com.ruoyi.project.system.service.WxSendService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Objects;

@Service
@Slf4j
@RequiredArgsConstructor
public class WxSendServiceImpl implements WxSendService {

    @Autowired
    private final RestTemplate restTemplate;

    @Autowired
    private final WxAccessTokenManager wxAccessTokenManager;

    @Override
    public Boolean sendMessage(String templateId, String openId, String page, String data) {
        boolean isSend = false;
        //获取accessToken
        String accessToken = wxAccessTokenManager.getAccessToken();
        if (StringUtils.isBlank(accessToken)) {
            log.error("微信accessToken不能为空：{}", accessToken);
            wxAccessTokenManager.refreshToken();
            accessToken = wxAccessTokenManager.getAccessToken();
        }
        String url = String.format("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s", accessToken);
        JSONObject postData = new JSONObject(true);
        try {
            postData.put("touser", openId);
            postData.put("template_id", templateId);
            postData.put("page", page);
            postData.put("data", JSON.parseObject(data));
            postData.put("miniprogram_state", "formal");
            postData.put("lang", "zh_CN");
            log.info("发送消息内容:{}", postData.toJSONString());
            JSONObject body = restTemplate.postForEntity(url, postData, JSONObject.class).getBody();
            if (Objects.nonNull(body)) {
                log.info("openId:" + openId + "发送消息返回内容:" + body.toJSONString());
                isSend = true;
            }
        } catch (Exception e) {
            isSend = false;
            log.error("openId:" + openId + "发送消息异常报错:" + e);
        }

        return isSend;
    }
}
